/*-------------------------------------------
 * 
 * getch.c: 模拟实现getch()
 *
 * *----------------------------------------*/
#include <stdio.h>
#include <termios.h> // 操作终端
#include <unistd.h>
#include <assert.h>
#include <string.h>

#include "getch.h"

int getch()
{
    int ch, res;
    struct termios org_opts, new_opts;
    // 保留终端原来设置
    res = tcgetattr(STDIN_FILENO, &org_opts);
    assert(res == 0);
    // 从新设置终端参数
    memcpy(&new_opts, &org_opts, sizeof(new_opts));
    // new_opts.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | ECHOPRT | ECHOKE | ICRNL);
    new_opts.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | ECHOKE | ICRNL);
    tcsetattr(STDIN_FILENO, TCSANOW, &new_opts);
    ch = getchar();
    // 恢复中断设置
    res = tcsetattr(STDIN_FILENO, TCSANOW, &org_opts);
    assert(res == 0);
    return ch;
}


